package com.itlong.cloud.controller.system;

import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperatePaperGetVO;
import com.itlong.cloud.POJO.VO.operate.OperatePaperImgGetVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.noncore.operate.IOperatePaperServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *     说明书管理控制器
 * </desc>
 *
 * @createDate 2018/06/27
 */
@RestController
@RequestMapping("/system/paper")
@RefreshScope
public class OperatePaperController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(OperatePaperController.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IOperatePaperServiceClient iOperatePaperServiceClient;  // 说明书管理暴露接口

    /**
     * <desc>
     *     分页获取说明书信息
     * </desc>
     *
     * @param operatePaperGetPageDTO 说明书管理分页查询说明书数据传输对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/27
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping(path = "getPapersByPage")
    public Object getPapersByPage(OperatePaperGetPageDTO operatePaperGetPageDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operatePaperGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperatePaperGetPageDTO.class,request);
            //判断参数合法性
            if (null == operatePaperGetPageDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(operatePaperGetPageDTO.getCreateStartTime()) && StringUtils.isNotBlank(operatePaperGetPageDTO.getCreateEndTime())) {
                Date createStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(operatePaperGetPageDTO.getCreateStartTime());
                Date createEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(operatePaperGetPageDTO.getCreateEndTime());
                // 创建开始时间必须小于创建结束时间
                if (createStartTime.after(createEndTime)) {
                    return new MessageVO(OperateErrorCodeEnum.PAPER_SEARCH_CREATE_TIME_AVAILABLE_ERR.getErrorCode());
                }
            }
            Page<OperatePaperGetVO> page = iOperatePaperServiceClient.getPapersByPage(operatePaperGetPageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书getPage】获取分页列表失败", e);
        }
    }

    /**
     * <desc>
     *     精确查询单个说明书信息
     * </desc>
     *
     * @param operatePaperGetOneDTO 说明书管理单个精确查询说明书数据传输对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/28
     */
    @ResponseBody
    @PostMapping(path = "getOnePaper")
    public Object getOnePaper(OperatePaperGetOneDTO operatePaperGetOneDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operatePaperGetOneDTO= HttpProtocolUtil.parseRequestParamToDTO(OperatePaperGetOneDTO.class,request);
            // 判断参数合法性
            if (null == operatePaperGetOneDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            // 条件必须有一个
            if (StringUtils.isBlank(operatePaperGetOneDTO.getPaperId()) && StringUtils.isBlank(operatePaperGetOneDTO.getPaperNumber())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(operatePaperGetOneDTO.getPaperNumber())) {
                // 若传入参数为paperNumber，则进行补0操作
                int paperNumber = StringHandlerUtil.strToIntDef(operatePaperGetOneDTO.getPaperNumber(), -1);
                if (!NumberHandlerUtil.isInRange(paperNumber,1,99999)) {
                    return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_INVALID_ERR.getErrorCode());
                }
                operatePaperGetOneDTO.setPaperNumber(NumberHandlerUtil.numFormatToString(paperNumber,5));
            }
            OperatePaperGetVO operatePaperGetVO = iOperatePaperServiceClient.getOnePaper(operatePaperGetOneDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operatePaperGetVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书getOnePaper】查询单个说明书信息失败", e);
        }
    }

    /**
     * <desc>
     *     保存说明书信息
     * </desc>
     *
     * @param operatePaperSaveDTO 说明书管理保存说明书数据传输对象
     * @param request HTTP协议请求对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/28
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_OPERATE_SAVE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "savePaper")
    public Object savePaper(OperatePaperSaveDTO operatePaperSaveDTO, HttpServletRequest request){
        try {
            operatePaperSaveDTO= HttpProtocolUtil.parseRequestParamToDTO(OperatePaperSaveDTO.class,request);
//            LOG.error("【保存说明书】接收到请求");
            // 判断参数的合法性
            if (null == operatePaperSaveDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperSaveDTO.getPaperTitle())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_TITLE_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperSaveDTO.getPaperNo())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NO_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperSaveDTO.getPaperNumber())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperSaveDTO.getPaperType())) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_TYPE_EMPTY_ERR.getErrorCode());
            }
            if (operatePaperSaveDTO.getLogo() == null || (operatePaperSaveDTO.getLogo() != 1 && operatePaperSaveDTO.getLogo() != 0)) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_LOGO_EMPTY_ERR.getErrorCode());
            }
            // 说明书编号前置补0
            int paperNumber = StringHandlerUtil.strToIntDef(operatePaperSaveDTO.getPaperNumber(), -1);
            if (!NumberHandlerUtil.isInRange(paperNumber,1,99999)) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_INVALID_ERR.getErrorCode());
            }
            operatePaperSaveDTO.setPaperNumber(NumberHandlerUtil.numFormatToString(paperNumber,5));
            // 校验说明书编号是否存在
            OperatePaperGetOneDTO operatePaperGetOneDTO = new OperatePaperGetOneDTO();
            operatePaperGetOneDTO.setPaperNumber(operatePaperSaveDTO.getPaperNumber());
            OperatePaperGetVO onePaper = iOperatePaperServiceClient.getOnePaper(operatePaperGetOneDTO);
            if (onePaper != null){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_EXIST_ERR.getErrorCode());
            }
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart){
//                LOG.error("【保存说明书】开始上传图片");
                MessageVO messageVO = this.uploadPaperImgForSave(request,operatePaperSaveDTO);
                if (messageVO != null){
                    return messageVO;
                }
            } else {
                return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_EMPTY_ERR.getErrorCode());
            }
//            LOG.error("【保存说明书】调用Client中方法");
            Integer intReturn = iOperatePaperServiceClient.savePaper(operatePaperSaveDTO);
            if (intReturn == null || intReturn == 0){
                return new MessageVO(OperateErrorCodeEnum.PAPER_QR_CODE_CREATE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书savePaper】保存说明书信息失败", e);
        }
    }

    /**
     * <desc>
     *      修改说明书信息
     * </desc>
     *
     * @param operatePaperUpdateDTO 说明书管理修改说明书数据传输对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/29
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_OPERATE_UPDATE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "updatePaper")
    public Object updatePaper(OperatePaperUpdateDTO operatePaperUpdateDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operatePaperUpdateDTO= HttpProtocolUtil.parseRequestParamToDTO(OperatePaperUpdateDTO.class,request);
            // 判断参数的合法性
            if (null == operatePaperUpdateDTO || StringUtils.isBlank(operatePaperUpdateDTO.getPaperId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperUpdateDTO.getPaperTitle())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_TITLE_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperUpdateDTO.getPaperNo())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NO_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperUpdateDTO.getPaperNumber())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(operatePaperUpdateDTO.getPaperType())) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_TYPE_EMPTY_ERR.getErrorCode());
            }
            if (operatePaperUpdateDTO.getLogo() == null || (operatePaperUpdateDTO.getLogo() != 1 && operatePaperUpdateDTO.getLogo() != 0)) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_LOGO_EMPTY_ERR.getErrorCode());
            }
            // 说明书编号前置补0
            int paperNumber = StringHandlerUtil.strToIntDef(operatePaperUpdateDTO.getPaperNumber(), -1);
            if (!NumberHandlerUtil.isInRange(paperNumber,1,99999)) {
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_INVALID_ERR.getErrorCode());
            }
            operatePaperUpdateDTO.setPaperNumber(NumberHandlerUtil.numFormatToString(paperNumber,5));
            // 校验说明书编号是否存在
            OperatePaperGetOneDTO operatePaperGetOneDTO = new OperatePaperGetOneDTO();
            operatePaperGetOneDTO.setPaperNumber(operatePaperUpdateDTO.getPaperNumber());
            OperatePaperGetVO onePaper = iOperatePaperServiceClient.getOnePaper(operatePaperGetOneDTO);
            // 查询出来的结果不是将要修改的结果
            if (onePaper != null && !StringHandlerUtil.compareStrWithOutEmpty(onePaper.getPaperId(),operatePaperUpdateDTO.getPaperId())){
                return new MessageVO(OperateErrorCodeEnum.PAPER_NUMBER_EXIST_ERR.getErrorCode());
            }

            Integer intReturn = iOperatePaperServiceClient.updatePaper(operatePaperUpdateDTO);
            if (intReturn == null || intReturn == 0){
                return new MessageVO(OperateErrorCodeEnum.PAPER_QR_CODE_CREATE_ERR.getErrorCode());
            }
            return new MessageVO(operatePaperUpdateDTO.getPaperId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书updatePaper】修改说明书信息失败", e);
        }
    }

    /**
     * <desc>
     *      删除说明书信息
     * </desc>
     *
     * @param paperId 说明书id
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/29
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_OPERATE_DELETE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "deletePaper")
    public Object deletePaper(String paperId){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            paperId=request.getAttribute("paperId")==null?null:request.getAttribute("paperId").toString();
            if (StringUtils.isBlank(paperId)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iOperatePaperServiceClient.deletePaper(paperId);
            return new MessageVO(paperId,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书deletePaper】删除说明书信息失败", e);
        }
    }

    /**
     * <desc>
     *      查看说明书详情
     * </desc>
     *
     * @param operatePaperImgGetDTO 查询参数
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/07/02
     */
    @ResponseBody
    @PostMapping(path = "getPaperImg")
    public Object getPaperImg(OperatePaperImgGetDTO operatePaperImgGetDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operatePaperImgGetDTO=HttpProtocolUtil.parseRequestParamToDTO(OperatePaperImgGetDTO.class,request);
            if (operatePaperImgGetDTO == null ||
                    (StringUtils.isBlank(operatePaperImgGetDTO.getPaperId()) && StringUtils.isBlank(operatePaperImgGetDTO.getPaperNumber()))) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperatePaperImgGetVO operatePaperImgGetVO = iOperatePaperServiceClient.getPaperImg(operatePaperImgGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operatePaperImgGetVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书getPaperImg】查看说明书详情失败", e);
        }
    }

    /**
     * <desc>
     *      添加说明书详情图片
     * </desc>
     *
     * @param operatePaperImgSaveOrUpdateDTO 说明书管理保存说明书详情数据传输对象
     * @param request HTTP协议请求对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/07/02
     */
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_IMG_OPERATE_SAVE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "savePaperImg")
    public Object savePaperImg(OperatePaperImgSaveOrUpdateDTO operatePaperImgSaveOrUpdateDTO, HttpServletRequest request){
        try {
            operatePaperImgSaveOrUpdateDTO=HttpProtocolUtil.parseRequestParamToDTO(OperatePaperImgSaveOrUpdateDTO.class,request);
            if (operatePaperImgSaveOrUpdateDTO == null || StringUtils.isBlank(operatePaperImgSaveOrUpdateDTO.getPaperId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperatePaperSaveDTO operatePaperSaveDTO = new OperatePaperSaveDTO();
            MessageVO messageVO = this.uploadPaperImgForSave(request, operatePaperSaveDTO);
            if (messageVO != null){
                return messageVO;
            }
            List<OperatePaperImgSaveDTO> operatePaperImgSaveDTOS = operatePaperSaveDTO.getOperatePaperImgSaveDTOS();
            if (operatePaperImgSaveDTOS == null || operatePaperImgSaveDTOS.isEmpty()){
                return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_UPLOAD_ERR.getErrorCode());
            }
            operatePaperImgSaveOrUpdateDTO.setOperatePaperImgSaveDTOS(operatePaperImgSaveDTOS);
            iOperatePaperServiceClient.savePaperImg(operatePaperImgSaveOrUpdateDTO);
            return new MessageVO(operatePaperImgSaveOrUpdateDTO.getPaperId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书savePaperImg】添加说明书详情失败", e);
        }
    }

    /**
     * <desc>
     *      编辑(替换)说明书详情图片
     * </desc>
     *
     * @param operatePaperImgSaveOrUpdateDTO 说明书管理修改说明书详情数据传输对象
     * @param request HTTP协议请求对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/07/02
     */
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_IMG_OPERATE_UPDATE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "updatePaperImg")
    public Object updatePaperImg(OperatePaperImgSaveOrUpdateDTO operatePaperImgSaveOrUpdateDTO, HttpServletRequest request){
        try {
            operatePaperImgSaveOrUpdateDTO=HttpProtocolUtil.parseRequestParamToDTO(OperatePaperImgSaveOrUpdateDTO.class,request);
            if (operatePaperImgSaveOrUpdateDTO == null || operatePaperImgSaveOrUpdateDTO.getId() == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperatePaperSaveDTO operatePaperSaveDTO = new OperatePaperSaveDTO();
            MessageVO messageVO = this.uploadPaperImgForSave(request, operatePaperSaveDTO);
            if (messageVO != null){
                return messageVO;
            }
            List<OperatePaperImgSaveDTO> operatePaperImgSaveDTOS = operatePaperSaveDTO.getOperatePaperImgSaveDTOS();
            if (operatePaperImgSaveDTOS == null || operatePaperImgSaveDTOS.isEmpty()){
                return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_UPLOAD_ERR.getErrorCode());
            }
            operatePaperImgSaveOrUpdateDTO.setOperatePaperImgSaveDTOS(operatePaperImgSaveDTOS);
            iOperatePaperServiceClient.updatePaperImg(operatePaperImgSaveOrUpdateDTO);
            return new MessageVO(operatePaperImgSaveOrUpdateDTO.getId().toString(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书updatePaperImg】修改说明书详情失败", e);
        }
    }

    /**
     * <desc>
     *      删除说明书详情
     * </desc>
     *
     * @param operatePaperImgDeleteDTO 删除说明书详情数据传输对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/07/02
     */
    @LoggerInfo(operateDesc = LogDescConstant.PAPER_IMG_OPERATE_DELETE_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "deletePaperImg")
    public Object deletePaperImg(OperatePaperImgDeleteDTO operatePaperImgDeleteDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operatePaperImgDeleteDTO=HttpProtocolUtil.parseRequestParamToDTO(OperatePaperImgDeleteDTO.class,request);
            if (operatePaperImgDeleteDTO == null ||
                    (StringUtils.isBlank(operatePaperImgDeleteDTO.getPaperId()) && operatePaperImgDeleteDTO.getId() == null)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iOperatePaperServiceClient.deletePaperImg(operatePaperImgDeleteDTO);
            return new MessageVO(StringUtils.isBlank(operatePaperImgDeleteDTO.getPaperId())?operatePaperImgDeleteDTO.getId().toString():operatePaperImgDeleteDTO.getPaperId(),
                    BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_说明书deletePaperImg】删除说明书详情失败", e);
        }
    }

    /**
     * <desc>
     *     保存说明书上传说明书详情方法
     * </desc>
     *
     * @param request HTTP协议对象
     * @param operatePaperSaveDTO 说明书管理保存说明书数据传输对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/06/28
     */
    private MessageVO uploadPaperImgForSave(HttpServletRequest request, OperatePaperSaveDTO operatePaperSaveDTO) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        List<OperatePaperImgSaveDTO> operatePaperImgSaveDTOList = new ArrayList<>();
        String imgExt = "jpg|jpeg|png|bmp|BMP|GIF|JPG|PNG|JPEG";
        if (multipartFileMap.isEmpty()){
            return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_EMPTY_ERR.getErrorCode());
        }
        for(String fileKey : multipartFileMap.keySet()){
            List<MultipartFile> fileList = multipartRequest.getFiles(fileKey);
            Iterator<MultipartFile> fileIterator = fileList.iterator();
            while (fileIterator.hasNext()){
                MultipartFile paperFile = fileIterator.next();
                OperatePaperImgSaveDTO operatePaperImgSaveDTO = new OperatePaperImgSaveDTO();
                String filename = paperFile.getOriginalFilename();
                filename = filename.replaceAll("-","_");
                int a = filename.lastIndexOf("_");
                int b = filename.lastIndexOf(".");
                String c= filename.substring(a+1,b);
                Integer showOrder = StringHandlerUtil.strToIntDef(c, -1);
                if (showOrder == -1){
                    return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_NAME_INVALID_ERR.getErrorCode());
                }
                operatePaperImgSaveDTO.setShowOrder(showOrder);

                InputStream fileStream = paperFile.getInputStream();
                ByteArrayOutputStream streamForClone = this.cloneInputStream(fileStream);
                String fileUrl;
                try {
                    // 限制图片类型，需求已取消
                    /*InputStream checkStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    try {
                        ImageInputStream iis = ImageIO.createImageInputStream(checkStream);
                        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
                        while(imageReaders.hasNext()){
                            ImageReader reader = imageReaders.next();
                            if (!StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(reader.getFormatName(),"jpg")){
                                return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_TYPE_INVALID_ERR.getErrorCode());
                            }
                        }
                    } finally {
                        checkStream.close();
                    }*/
                    String fileType = StringHandlerUtil.copySubStr(filename, filename.lastIndexOf('.') + 1, filename.length());
                    if (StringUtils.isBlank(fileType) || (!imgExt.contains(fileType))) {
                        return new MessageVO(OperateErrorCodeEnum.IMAGE_TYPE_ANVALID_ERR.getErrorCode());
                    }

                    InputStream upLoadStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    try {
                        fileUrl = this.uploadFile(upLoadStream, filename);
                    }finally {
                        upLoadStream.close();
                    }

                } finally {
                    streamForClone.close();
                }
                if (StringUtils.isBlank(fileUrl)) {
                    return new MessageVO(OperateErrorCodeEnum.PAPER_IMG_UPLOAD_ERR.getErrorCode());
                }
                operatePaperImgSaveDTO.setPaperUrl(fileUrl);
                operatePaperImgSaveDTOList.add(operatePaperImgSaveDTO);
            }
        }
        operatePaperSaveDTO.setOperatePaperImgSaveDTOS(operatePaperImgSaveDTOList);
        return null;
    }

    /**
     * <desc>
     *     拷贝流
     * </desc>
     *
     * @param inputStream 输入流
     * @return 拷贝后的输出流
     * @author wangzhi
     * @createDate 2018/06/28
     */
    private ByteArrayOutputStream cloneInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream forCloneStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readLength = 0;
        while ((readLength = inputStream.read(buffer)) != -1) {
            forCloneStream.write(buffer, 0, readLength);
        }
        forCloneStream.flush();
        return forCloneStream;
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2018/06/28
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName,fileName.lastIndexOf('.')+1,fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.OPERATE_PAPER_IMG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
